# -*- coding: utf-8 -*-
# @时间：2023/11/8 9:23
# @作者：CJiaの可乐哥
# @文件名：dept
# @软件：Pycharm2023
from typing import List

from django.shortcuts import get_object_or_404
from ninja import Router, Schema, Query, Field, ModelSchema
from ninja.pagination import paginate
from system.models import Dept

from utils.cj_ninja import MyPagination
from utils.cj_curd import retrieve, delete, update, status
from utils.cj_tree import list_to_route, list_to_tree
from utils.cj_response import SuccessResponse

router = Router()


class Filters(Schema):
    id: str = Field(None, alias="id")
    name: str = Field(None, alias="name")
    status: bool = Field(None, alias="status")


class DeptSchemaIn(ModelSchema):
    class Config:
        model = Dept
        model_exclude = ['id', 'parent', 'create_datetime', 'update_datetime']


class DeptSchemaOut(ModelSchema):
    class Config:
        model = Dept
        model_fields = "__all__"


@router.delete("/dept/{dept_id}")
def delete_dept(request, dept_id: int):
    request.types = "sys:dept:delete"
    # 调用删除方法
    result = delete(request, dept_id, Dept)
    # 返回结果
    return result


@router.put('/dept/{dept_id}', response=DeptSchemaOut)
def update_dept(request, dept_id: int, data: DeptSchemaIn):
    request.types = "sys:dept:update"
    # 调用修改方法
    result = update(request, dept_id, data, Dept)
    # 返回结果
    return result


@router.put("/dept/status/{dept_id}")
def status_dept(request, dept_id: int):
    request.types = "sys:dept:update"
    # 调用修改状态方法
    result = status(request, dept_id, Dept)
    # 返回结果
    return result


@router.get("/dept/{dept_id}", response=DeptSchemaOut)
def get_dept(request, dept_id: int):
    dept = get_object_or_404(Dept, id=dept_id)
    return dept


@router.get("/dept/list/tree", response=List[DeptSchemaOut])
def list_dept_tree(request, filters: Filters = Query(...)):
    qs = retrieve(request, Dept, filters).values()
    dept_tree = list_to_tree(list(qs))
    return SuccessResponse(data=dept_tree)
